/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  if (time.indexOf('01-01-01') > -1) {
    return '-'
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}
// 回显数据字典
export function selectDictLabel(datas, value) {
  var actions = []
  Object.keys(datas).map((key) => {
    if (datas[key].value === ('' + value)) {
      actions.push(datas[key].label)
      return false
    }
  })
  return actions.join('')
}
/**
 * @param {Array} filterVal
 * @param {Object} jsonData
 * @returns {string}
 */
export function formatJson(filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => {
    if (j === 'timestamp') {
      return parseTime(v[j])
    } else {
      return v[j]
    }
  }))
}
// 添加日期范围
export function addDateRange(params, dateRange) {
  var search = params
  search.beginTime = ''
  search.endTime = ''
  if (dateRange != null && dateRange !== '') {
    search.beginTime = this.dateRange[0]
    search.endTime = this.dateRange[1]
  }
  return search
}
// 查询列表
export function getItems(f, query) {
  query = query || { pageSize: 10000 }
  return f(query)
}

export function setItems(response, k, v) {
  const data = []
  k = k || 'id'
  v = v || 'name'
  if (response.data && response.data.list && response.data.list.length > 0) {
    response.data.list.forEach(e => {
      data.push({
        key: e[k].toString(),
        value: e[v].toString()
      })
    })
    return data
  }
}
/**
 * @description: 不为空的数据添加到请求体中
 * @param {Object}  postParams   过滤完成的数据
 * @param {Object}  obj   需要过滤的数据
 * @return {type} 该方法会改变postParams
 */
export function appendPostData(postParams, obj) {
  for (let i in obj) {
    if (obj.hasOwnProperty(i)) {
      if (obj[i] !== "") {
        postParams[i] = obj[i];
      }
    }
  }
  return postParams;
}
/**
 * @param {promise}
 * @return {arr}
 */
export function handlePromise(promise) {
  return promise.then(res => [undefined, res]).catch(err => [err, undefined]);
}

/*工具函数*/



//用于生成uuid
function S4() {
  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
export  function guid() {
  return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

export function GetQueryValue(queryName,query) {
  if (!query) {
    query = decodeURI(window.location.hash.substring(1));
  }
  if (query.indexOf("?") === -1) {
    return false;
  }
  query = query.split("?")[1];
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == queryName) {
      return pair[1];
    }
  }
  return null;
}
export const phoneReg = /^1([38]\d{1}|7[^0149]|6[6]|(4[05-79]|5[^4]|9[^024]))\d{8}$/;
//DES 加密
function byteToString(arr) {
  if (typeof arr === 'string') {
    return arr;
  }
  var str = '',
    _arr = arr;
  for (var i = 0; i < _arr.length; i++) {
    var one = _arr[i].toString(2),
      v = one.match(/^1+?(?=0)/);
    if (v && one.length == 8) {
      var bytesLength = v[0].length;
      var store = _arr[i].toString(2).slice(7 - bytesLength);
      for (var st = 1; st < bytesLength; st++) {
        store += _arr[st + i].toString(2).slice(2);
      }
      str += String.fromCharCode(parseInt(store, 2));
      i += bytesLength - 1;
    } else {
      str += String.fromCharCode(_arr[i]);
    }
  }
  return str;
}
export function encryptByDESModeCBCUtf8to64(keyCode,message,CryptoJS) {
  var key = keyCode; //密钥
  var iv = [21, 1, 11, 82, 22, 44, 55, 33];
  var ivString = byteToString(iv)
  var keyHex = CryptoJS.enc.Utf8.parse(key);
  var ivHex = CryptoJS.enc.Utf8.parse(ivString);
  var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

//判断今天是周几
export function getWeek(date) {
  var weekNum = new Date(date).getDay(),
    weekInChinese = '';
  if (weekNum == 1) {
    weekInChinese = '周一';
  } else if (weekNum == 2) {
    weekInChinese = '周二';
  } else if (weekNum == 3) {
    weekInChinese = '周三';
  } else if (weekNum == 4) {
    weekInChinese = '周四';
  } else if (weekNum == 5) {
    weekInChinese = '周五';
  } else if (weekNum == 6) {
    weekInChinese = '周六';
  } else if (weekNum == 0) {
    weekInChinese = '周日';
  }
  return weekInChinese;
}

//获取当天日期 YYYY-MM-DD
export function getDate() {
  var date = new Date();
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

export function getTime() {
  var time = new Date();
  var hours = time.getHours();
  hours = hours < 10 ? '0' + hours : hours
  var minute = time.getMinutes()
  minute = minute < 10 ? '0' + minute : minute
  var second = time.getSeconds()
  second = second < 10 ? '0' + second : second
  return [hours, minute, second].join(':')
}

export function compareDate (date1,date2,date3){
  var oDate1 = new Date(date1);
  var oDate2 = new Date(date2);
  var oDate3 = new Date(date3);
  // 设置 examBeginTime 的时间为当天的 00:00:00
  oDate1.setHours(0, 0, 0, 0);
  // 设置 examEndTime 的时间为当天的 23:59:59
  oDate3.setHours(23, 59, 59, 999);
  // console.log(oDate1)
  // console.log(oDate2)
  // console.log(oDate3)
  if(oDate1.getTime() <= oDate2.getTime() &&  oDate2.getTime() <= oDate3.getTime()){
    return true
  } else {
    return false
  }
}
export function compareDateTwo (date1,date2,eqFlag){
  var oDate1 = new Date(date1);
  var oDate2 = new Date(date2);
  if (eqFlag) {
    if(oDate1.getTime() <= oDate2.getTime()){
      return true
    } else {
      return false
    }
  }else {
    if(oDate1.getTime() < oDate2.getTime()){
      return true
    } else {
      return false
    }
  }
}
function PRCDate() {
  return new Date(new Date().getTime()+(parseInt(new Date().getTimezoneOffset()/60) + 8)*3600*1000);
}
/*时间格式转换*/
export function parseTime2(d,flag) {
  //Fri Sep 28 2018 00:00:00 GMT+0800 (中国标准时间) {}  转换为  2018-09-28 00:00:00
  d = new Date(d)
  var year=d.getFullYear();
  var month=change(d.getMonth()+1);
  var day=change(d.getDate());
  var hour=change(d.getHours());
  var minute=change(d.getMinutes());
  var second=change(d.getSeconds());
  function change(t){
    if(t<10){
      return "0"+t;
    }else{
      return t;
    }
  }
  if (flag) {
    const newDate = year+'-'+month+'-'+day;
    return newDate;
  }else {
    const newDate = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
    return newDate;
  }
}


export function parsetime(d,flag) {
  //Fri Sep 28 2018 00:00:00 GMT+0800 (中国标准时间) {}  转换为  2018-09-28 00:00:00
  d = new Date(d)
  var year=d.getFullYear();
  var month=change(d.getMonth()+1);
  var day=change(d.getDate());
  var hour=change(d.getHours());
  var minute=change(d.getMinutes());
  var second=change(d.getSeconds());
  function change(t){
    if(t<10){
      return "0"+t;
    }else{
      return t;
    }
  }
  if (flag) {
    const newDate = year+'/'+month+'/'+day;
    return newDate;
  }else {
    const newDate = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
    return newDate.substring(0, 18) + "0";
  }

}

/*计算前多少年*/
export function parseDate(d,cha) {
  //Fri Sep 28 2018 00:00:00 GMT+0800 (中国标准时间) {}  转换为  2018-09-28 00:00:00
  d = new Date(d)
  var year=d.getFullYear()-cha;
  var month=change(d.getMonth()+1);
  var day=change(d.getDate());
  function change(t){
    if(t<10){
      return "0"+t;
    }else{
      return t;
    }
  }
  const newDate ={
    year:year,
    month:month,
    day:day,
  }
  return newDate;
}
/*---------------时间相减----------------------*/

export function daysBetween(DateOne,DateTwo) {
  console.log(DateOne,DateTwo)
  var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));

  var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);

  var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));

  var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-'));

  var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-')+1);

  var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('-'));

  var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000);

  return cha;
}
/**/
export function getTimeLeft(datetimeTo){
  // 计算目标与现在时间差（毫秒）
  let time1 = new Date(datetimeTo).getTime();
  let time2 = new Date().getTime();
  let mss = time1- time2;
  let a=Math.floor(mss % (3600 * 1e3) % (1000 * 60) / 1e3);
  // console.log("两个时间减的"+a);
  // 将时间差（毫秒）格式为：天时分秒
  let days = parseInt(mss / (1000 * 60 * 60 * 24));
  let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = parseInt((mss % (1000 * 60)) / 1000);
  // return `<span class="training-time-countdown-num">${hours}</span><i>:</i><span class="training-time-countdown-num">${minutes}</span><i>:</i><span class="training-time-countdown-num">${seconds}</span>`
  return twoFn(hours) + ":" + twoFn(minutes) + ":" + twoFn(seconds);
}

export  function twoFn(v) {
  return v < 10 ? '0' + v : v;
}




/*指定一个数组截取几个，返回一个数组*/
export function getSpecifiedArray(array,num1,num2) {
  if (array instanceof  Array)
    return array.slice(num1,num2)
}
/*参数对象 param 进行序列化的函数  获取参数对象的所有键名
对每个键名和值进行 URI 编码
用 & 拼接成查询字符串*/
export function transParams(params) {
  return Object.keys(params)
    .map(key => {
      return `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    })
    .join('&')
}

/*===================为视屏列表数组根据他的视屏类型添加播放类型============*/
export function  getTypeName (array) {
  array.forEach((item,index) =>{
    if (item.classVideoType === "1"){
      item.typeName = '三分屏';
    }else if (item.classVideoType == '2') {
      item.typeName = '单视频';
    } else if (item.classVideoType == '3') {
      item.typeName = '微课'
    } else if (item.classVideoType == '4') {
      item.typeName = '音频';
    }
  })
  return array;
}

export function AutoNumberByLetter(vNumber) {
  vNumber = Number(vNumber) - 1;
  var vLetter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

  if (vNumber < 26)
    return vLetter[vNumber];
  else {
    var vInt = parseInt((vNumber + 1) / 26);
    var vRemainder = (vNumber + 1) % 26;
    if (vRemainder == 0) {
      vInt = vInt - 1;
      vRemainder = 26;
    }
    return vLetter[vInt - 1] + vLetter[vRemainder - 1];
  }
}
/**
 * 计算精度问题
 * 解决 2.3*100 计算机得到的不是230的问题
 * */
export const accMul=(arg1,arg2)=>{
  let m=0, s1='', s2='';
  if(arg1&&arg1!=null)
    s1=arg1.toString();

  if(arg2&&arg2!=null)
    s2=arg2.toString();

  try{m+=s1.split('.')[1].length}catch(e){}
  try{m+=s2.split('.')[1].length}catch(e){}

  return Number(s1.replace('.',''))*Number(s2.replace('.',''))/Math.pow(10,m);
}

//给Number类型增加一个mul方法，调用起来更加方便，以下类似
Number.prototype.mul = function (arg){
  return accMul(arg,this);
}

/*函数节流*/


export const getParms = function (e,data) {
  return e.$route.query[data]
}

export function myGetData(getData, times, delay) {
  return new Promise(function(resolve, reject) {
    var attempt = function () {
      getData().then(resolve).catch(function(erro) {
        console.log(`还有 ${times} 次尝试`)
        if (0 === times) {
          reject(erro)
        } else {
          times--;
          setTimeout(attempt(), delay)
        }
      })
    };
    attempt()
  })
}
//在HTML代码中提取文本内容，并去掉空格和回车等字符
export function setText(val) {
  if (val != null && val != "") {
    var re1 = new RegExp("<.+?>|&.+?;","g"); //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
    var msg = val.replace(re1,""); //执行替换成空字符
    msg = msg.replace(/\s/g,""); //去掉所有的空格（中文空格、英文空格都会被替换）
    msg = msg.replace(/[\r\n]/g,""); //去掉所有的换行符
    return msg; //获文本文字内容的前100个字符
  } else return ''
}

export function calPrice(num){
  var num1 = Number(num);
  if (num1 != 0 && num){
    return num1 / 100
  } else {
    return num
  }
}
//将字符进行转义
export function unEscapeHTML(html) {
  html= "" +html;
  return html.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&ldquo;/g, '"').replace(/&rdquo;/g, '"').replace(/&apos;/g, "'").replace(/&mdash;/g, "—");
};
//运算函数
export function operationFn() {

  //判断obj是否为一个整数
  function isInteger(obj) {
    return Math.floor(obj) === obj
  }

  /*
     * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
     * @param floatNum {number} 小数
     * @return {object}
     *   {times:100, num: 314}
     */
  function toInteger(floatNum) {
    var ret = {times: 1, num: 0}
    if (isInteger(floatNum)) {
      ret.num = floatNum
      return ret
    }
    var strfi  = floatNum + ''
    var dotPos = strfi.indexOf('.')
    var len    = strfi.substr(dotPos+1).length
    var times  = Math.pow(10, len)
    var intNum = parseInt(floatNum * times + 0.5, 10)
    ret.times  = times
    ret.num    = intNum
    return ret
  }

  /*
     * 核心方法，实现加减乘除运算，确保不丢失精度
     * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
     *
     * @param a {number} 运算数1
     * @param b {number} 运算数2
     * @param digits {number} 精度，保留的小数点数，比如 2, 即保留为两位小数
     * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
     *
     */
  function operation(a, b, digits, op) {
    var o1 = toInteger(a)
    var o2 = toInteger(b)
    var n1 = o1.num
    var n2 = o2.num
    var t1 = o1.times
    var t2 = o2.times
    var max = t1 > t2 ? t1 : t2
    var result = null
    switch (op) {
      case 'add':
        if (t1 === t2) { // 两个小数位数相同
          result = n1 + n2
        } else if (t1 > t2) { // o1 小数位 大于 o2
          result = n1 + n2 * (t1 / t2)
        } else { // o1 小数位 小于 o2
          result = n1 * (t2 / t1) + n2
        }
        return result / max
      case 'subtract':
        if (t1 === t2) {
          result = n1 - n2
        } else if (t1 > t2) {
          result = n1 - n2 * (t1 / t2)
        } else {
          result = n1 * (t2 / t1) - n2
        }
        return result / max
      case 'multiply':
        result = (n1 * n2) / (t1 * t2)
        return result
      case 'divide':
        result = (n1 / n2) * (t2 / t1)
        return result
    }
  }

  // 加减乘除的四个接口
  function add(a, b, digits) {
    return operation(a, b, digits, 'add')
  }
  function subtract(a, b, digits) {
    return operation(a, b, digits, 'subtract')
  }
  function multiply(a, b, digits) {
    return operation(a, b, digits, 'multiply')
  }
  function divide(a, b, digits) {
    return operation(a, b, digits, 'divide')
  }

  // exports
  return {
    add: add,
    subtract: subtract,
    multiply: multiply,
    divide: divide
  }
};


//用于限制一个函数在一定时间内多次触发时只执行最后一次。
/*callback：要执行的函数
duration：等待时间，即触发后延迟执行的时间
isFirstExecution：是否在第一次触发时立即执行
*/
var  debounceTimer = null;
export function debounce(callback, duration, isFirstExecution) {
  return function (...args) {
    var  ctx = this;
    var  delay = function () {
      debounceTimer = null;
      console.log('定时器函数执行了')
      if (!isFirstExecution) callback.apply(ctx, args);
    };
    var executeNow = isFirstExecution && !debounceTimer;
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(delay, duration);
    if (executeNow) callback.apply(ctx, args);
  };
};


export function changeNumMoneyToChinese(money) {
  var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
  var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
  var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
  var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
  var cnInteger = "整"; //整数金额时后面跟的字符
  var cnIntLast = "元"; //整型完以后的单位
  var maxNum = 999999999999999.9999; //最大处理的数字
  var IntegerNum; //金额整数部分
  var DecimalNum; //金额小数部分
  var ChineseStr = ""; //输出的中文金额字符串
  var parts; //分离金额后用的数组，预定义
  var Symbol = ""; //正负值标记
  if (money == "") {
    return "";
  }

  money = parseFloat(money);
  if (money >= maxNum) {
    alert('超出最大处理数字');
    return "";
  }
  if (money == 0) {
    ChineseStr = cnNums[0] + cnIntLast + cnInteger;
    return ChineseStr;
  }
  if (money < 0) {
    money = -money;
    Symbol = "负 ";
  }
  money = money.toString(); //转换为字符串
  if (money.indexOf(".") == -1) {
    IntegerNum = money;
    DecimalNum = '';
  } else {
    parts = money.split(".");
    IntegerNum = parts[0];
    DecimalNum = parts[1].substr(0, 4);
  }
  if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
    var zeroCount = 0;
    var IntLen = IntegerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = IntegerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          ChineseStr += cnNums[0];
        }
        zeroCount = 0; //归零
        ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        ChineseStr += cnIntUnits[q];
      }
    }
    ChineseStr += cnIntLast;
    //整型部分处理完毕
  }
  if (DecimalNum != '') { //小数部分
    var decLen = DecimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = DecimalNum.substr(i, 1);
      if (n != '0') {
        ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (ChineseStr == '') {
    ChineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (DecimalNum == '') {
    ChineseStr += cnInteger;
  }
  ChineseStr = Symbol + ChineseStr;

  return ChineseStr;
}
